<?php

namespace app\common\service;

use EasyWeChat\Factory;
use think\Exception;
use think\facade\Log;
use WeChat\Oauth;

class WxService
{
    protected $app;

    protected $config;

    function __construct()
    {
        $this->config = [
            'token' => sysconf('wechat_token'),
            'appid' => sysconf('wechat_appid'),
            'appsecret' => sysconf('wechat_appsecret'),
            'encodingaeskey' => sysconf('wechat_encodingaeskey'),
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => sysconf('wechat_mch_id'),
            'mch_key' => sysconf('wechat_mch_key'),
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => sysconf('wechat_mch_ssl_key'),
            'ssl_cer' => sysconf('wechat_mch_ssl_cer'),
        ];
    }

    public static function getMiniProgram()
    {
        $config = [
            'app_id' => sysconf("wemini_appid"),
            'secret' => sysconf("wemini_appsecret"),
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => env("runtime_path") . '/log/wechat.log',
            ],
        ];
        return Factory::miniProgram($config);
    }

    public function wxOauth($redirect_url, $state)
    {
        $wechat = new Oauth($this->config);
        return $wechat->getOauthRedirect($redirect_url, $state, "snsapi_userinfo");
    }

    public function getWxInfo()
    {
        $wechat = new Oauth($this->config);
        try {
            $token = $wechat->getOauthAccessToken();
            return $wechat->getUserInfo($token['access_token'], $token['openid']);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }

    }

}